package com.my.lucky.ui;

import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.swing.*;
import java.awt.*;
import java.util.logging.Logger;
import java.util.logging.SimpleFormatter;

@Slf4j
//@Component
public class MainWindow {
    //   private static final Logger logger = Logger.getLogger(MainWindow.class.getName());
    private final ApplicationContext applicationContext;
    private JFrame mainFrame;
    private JTextArea logArea;

    public MainWindow(ApplicationContext applicationContext) {
        this.applicationContext = applicationContext;
    }

    @PostConstruct
    public void init() {
        // 确保在EDT线程中创建和显示GUI
        SwingUtilities.invokeLater(() -> {
            mainFrame = new JFrame("量化系统");
            mainFrame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
            mainFrame.setSize(1024, 768);
            mainFrame.setLocationRelativeTo(null);  // 居中显示

            // 设置窗口图标
            ImageIcon icon = new ImageIcon(getClass().getResource("/icons/app-icon.png"));
            if (icon.getImage() != null) {
                mainFrame.setIconImage(icon.getImage());
            }

            // 添加关闭窗口监听器
            mainFrame.addWindowListener(new WindowCloseListener(applicationContext, mainFrame));

            // 创建主面板
            JPanel mainPanel = new JPanel(new BorderLayout());

            // 创建日志区域
            logArea = new JTextArea();
            logArea.setEditable(false);
            logArea.setFont(new Font(Font.MONOSPACED, Font.PLAIN, 12));
            logArea.setBackground(new Color(240, 240, 240));

            // 创建滚动面板
            JScrollPane scrollPane = new JScrollPane(logArea);

            // 设置日志处理器
            SwingLogHandler logHandler = new SwingLogHandler(logArea, 1000);
            logHandler.setFormatter(new SimpleFormatter());
            Logger.getLogger("").addHandler(logHandler);

            // 直接将日志区域添加到主面板
            mainPanel.add(scrollPane, BorderLayout.CENTER);
            mainFrame.setContentPane(mainPanel);

            mainFrame.setVisible(true);

            // 测试日志输出
            log.info("程序启动成功！");
        });
    }

    public JFrame getMainFrame() {
        return mainFrame;
    }

    public JTextArea getLogArea() {
        return logArea;
    }
} 